package cgroups

import (
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"os"
	"path"
	"strconv"
)

type MemorySubSystem struct {
}

func (m *MemorySubSystem) Name() string {
	return "memory"
}

func (m *MemorySubSystem) Set(subPath string, res *ResourceLimit) (err error) {
	if res.Memory == "" {
		return
	}

	var cgroupPath string
	if cgroupPath, err = GetGroupPath(subPath, m.Name(), true); err != nil {
		return err
	}

	if err = ioutil.WriteFile(path.Join(cgroupPath, "memory.limit_in_bytes"), []byte(res.Memory), 0644); err != nil {
		logrus.Info("set memory limit failure: %v", err)
	}
	return
}

func (m *MemorySubSystem) Apply(SubPath string, pid int) (err error) {
	var groupPath string
	if groupPath, err = GetGroupPath(SubPath, m.Name(), false); err != nil {
		return err
	}

	return ioutil.WriteFile(path.Join(groupPath, "tasks"), []byte(strconv.Itoa(pid)), 0644)
}

func (m *MemorySubSystem) Remove(SubPath string) (err error) {
	var groupPath string
	if groupPath, err = GetGroupPath(SubPath, m.Name(), false); err != nil {
		return err
	}

	return os.Remove(groupPath)
}
